package jtokyotyrant.protocol;

import java.lang.InterruptedException;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CommandFuture<T> implements Future<T> {
    private final Command<T> command;
    private final ExecutorService executor;
    private final Future<T> future;

    public CommandFuture(Command<T> command) {
        this.command = command;
        this.executor = Executors.newSingleThreadExecutor();
        this.future = executor.submit(command);
    }

    public boolean isCancelled() {
        return future.isCancelled();
    }

    public boolean isDone() {
        return future.isDone();
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        return future.cancel(mayInterruptIfRunning);
    }

    public T get() throws InterruptedException, ExecutionException {
        T ret = null;
        try {
            ret = future.get();
        }
        finally {
            executor.shutdown();
        }
        return ret;
    }

    public T get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        T ret = null;
        try {
            ret = future.get(timeout, unit);
        }
        finally {
            executor.shutdown();
        }
        return ret;
    }
}
